package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.dto.request.BannerRequest;
import com.papercutting.platform.entity.Banner;
import com.papercutting.platform.service.BannerService;
import com.papercutting.platform.util.ImageUrlUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 轮播图控制器
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@CrossOrigin
public class BannerController {
    
    private final BannerService bannerService;
    private final ImageUrlUtil imageUrlUtil;
    
    /**
     * 获取启用的轮播图列表（前端使用）
     */
    @GetMapping("/banner/active")
    public Result<List<Banner>> getActiveBanners() {
        List<Banner> banners = bannerService.findByStatusAndTimeRange(1, LocalDateTime.now());
        // 处理图片URL
        banners.forEach(banner -> {
            banner.setImageUrl(imageUrlUtil.processImageUrl(banner.getImageUrl()));
        });
        return Result.success(banners);
    }
    
    /**
     * 获取轮播图列表（新接口，兼容前端 carousel 调用）
     */
    @GetMapping("/carousel/list")
    public Result<List<Banner>> getCarouselList() {
        List<Banner> banners = bannerService.findByStatusAndTimeRange(1, LocalDateTime.now());
        // 处理图片URL
        banners.forEach(banner -> {
            banner.setImageUrl(imageUrlUtil.processImageUrl(banner.getImageUrl()));
        });
        return Result.success(banners);
    }
    
    /**
     * 获取轮播图列表（管理端，支持分页和搜索）
     */
    @GetMapping("/banners")
    public Result<Map<String, Object>> getBanners(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Integer linkType,
            @RequestParam(required = false) Integer status) {
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Banner> bannerPage = bannerService.findAll(pageable);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", bannerPage.getContent());
        result.put("total", bannerPage.getTotalElements());
        result.put("page", page);
        result.put("size", size);
        
        return Result.success(result);
    }
    
    /**
     * 获取轮播图详情
     */
    @GetMapping("/banners/{id}")
    public Result<Banner> getBannerById(@PathVariable Long id) {
        Banner banner = bannerService.findById(id);
        if (banner == null) {
            return Result.error("轮播图不存在");
        }
        return Result.success(banner);
    }
    
    /**
     * 创建轮播图
     */
    @PostMapping("/banners")
    public Result<Banner> createBanner(@RequestBody BannerRequest request) {
        Banner banner = new Banner();
        banner.setTitle(request.getTitle());
        banner.setDescription(request.getDescription());
        banner.setImageUrl(request.getImageUrl());
        banner.setLinkType(request.getLinkType());
        banner.setLinkUrl(request.getLinkUrl());
        banner.setTargetType(request.getTargetType());
        banner.setTargetId(request.getTargetId());
        banner.setSortOrder(request.getSortOrder());
        banner.setStatus(request.getStatus());
        banner.setStartTime(request.getStartTime());
        banner.setEndTime(request.getEndTime());
        
        Banner savedBanner = bannerService.save(banner);
        return Result.success(savedBanner);
    }
    
    /**
     * 更新轮播图
     */
    @PutMapping("/banners/{id}")
    public Result<Banner> updateBanner(@PathVariable Long id, @RequestBody BannerRequest request) {
        Banner banner = bannerService.findById(id);
        if (banner == null) {
            return Result.error("轮播图不存在");
        }
        
        banner.setTitle(request.getTitle());
        banner.setDescription(request.getDescription());
        banner.setImageUrl(request.getImageUrl());
        banner.setLinkType(request.getLinkType());
        banner.setLinkUrl(request.getLinkUrl());
        banner.setTargetType(request.getTargetType());
        banner.setTargetId(request.getTargetId());
        banner.setSortOrder(request.getSortOrder());
        banner.setStatus(request.getStatus());
        banner.setStartTime(request.getStartTime());
        banner.setEndTime(request.getEndTime());
        
        Banner savedBanner = bannerService.save(banner);
        return Result.success(savedBanner);
    }
    
    /**
     * 删除轮播图
     */
    @DeleteMapping("/banners/{id}")
    public Result<Void> deleteBanner(@PathVariable Long id) {
        Banner banner = bannerService.findById(id);
        if (banner == null) {
            return Result.error("轮播图不存在");
        }
        
        bannerService.deleteById(id);
        return Result.success("删除成功");
    }
    
    /**
     * 批量删除轮播图
     */
    @DeleteMapping("/banners/batch")
    public Result<Void> batchDeleteBanners(@RequestBody Map<String, List<Long>> request) {
        List<Long> ids = request.get("ids");
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的轮播图");
        }
        
        for (Long id : ids) {
            bannerService.deleteById(id);
        }
        
        return Result.success("批量删除成功");
    }
    
    /**
     * 更新轮播图状态
     */
    @PutMapping("/banners/{id}/status")
    public Result<Void> updateBannerStatus(@PathVariable Long id, @RequestBody Map<String, Integer> request) {
        Banner banner = bannerService.findById(id);
        if (banner == null) {
            return Result.error("轮播图不存在");
        }
        
        banner.setStatus(request.get("status"));
        bannerService.save(banner);
        
        return Result.success("状态更新成功");
    }
    
    /**
     * 更新轮播图排序
     */
    @PutMapping("/banners/{id}/sort")
    public Result<Void> updateBannerSort(@PathVariable Long id, @RequestBody Map<String, Integer> request) {
        Banner banner = bannerService.findById(id);
        if (banner == null) {
            return Result.error("轮播图不存在");
        }
        
        banner.setSortOrder(request.get("sortOrder"));
        bannerService.save(banner);
        
        return Result.success("排序更新成功");
    }
    
    /**
     * 获取轮播图统计信息
     */
    @GetMapping("/banners/stats")
    public Result<Map<String, Object>> getBannerStats() {
        List<Banner> allBanners = bannerService.findAll();
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCount", allBanners.size());
        stats.put("activeCount", allBanners.stream().mapToLong(b -> b.getStatus() == 1 ? 1 : 0).sum());
        stats.put("inactiveCount", allBanners.stream().mapToLong(b -> b.getStatus() == 0 ? 1 : 0).sum());
        stats.put("totalClicks", 0); // 可以后续添加点击统计
        
        return Result.success(stats);
    }
}